import axios from "axios";
const service = axios.create({
  baseURL: "https://m.nongmuren.com/scRanking",
  timeout: 10000 
});

service.interceptors.request.use(
  config => {
    const token = ''
    if (token) {
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    return response
  }, error => {
    this.$message.error('网络连接超时，请稍后再试！');
    return Promise.reject(error)
  })

// 设置全局请求方法,传接口参数和是否加载
function request (obj, isloading = false, successFun) {
  let loadingInstance = ''

  return service(obj).then(({ data }) => {
    if (isloading) {
      setTimeout(() => {
        loadingInstance.close()
      }, 300)
    }
    /** 如果有传过来一个function则请求成功且结果正确时执行此function，如果结果错误则自动处理错误结果 */
    if (typeof successFun === 'function') {
      console.log('data', data)
      if (data.code === 200) {
        successFun(data)
      } else {
        /** 处理错误结果 */
        this.$message.error(data.message);
      }
    }
    return data
  }).catch(err => {
    if (isloading) {
      loadingInstance.close()
    }
    return err
  })
}

function post (url, data = {}, successFun, isloading) {
  return request({
    url: url,
    method: 'post',
    data: data
  }, isloading, successFun)
}
function get (url, data = {}, successFun, isloading) {
  return request({
    url: url,
    method: 'get',
    params: data
  }, isloading, successFun)
}
function put (url, data = {}, successFun, isloading) {
  return request({
    url: url,
    method: 'put',
    data: data
  }, isloading, successFun)
}
function del (url, data = {}, successFun, isloading) {
  return request({
    url: url,
    method: 'delete',
    data: data,
    params: data
  }, isloading, successFun)
}

export { request, post, get, put, del }